package com.seio.edc.controller.system;

import com.nova.edc.model.system.CustomerInfo;
import com.nova.edc.model.system.PolicyEntity;
import com.nova.edc.service.system.CustomerInfoService;
import com.seio.edc.common.Constants;
import com.seio.edc.util.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "documents")
public class DocumentsContronller {

    private static Log log = LogFactory.getLog(PolicyEntity.class);

    @Autowired
    private CustomerInfoService customerInfoService;

    @RequestMapping(value = "documentsInit.shtml")
    public ModelAndView documentsInit(ModelMap modelMap, Integer companycode) {

        CustomerInfo customerInfo = customerInfoService.getByCompanyCode(companycode);
        File file = new File(Constants.UploadDocumentsPath + companycode);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        } else {
            List<PolicyEntity> fileNameList = new ArrayList<PolicyEntity>();
            List<String> fileNames = FileUtil.getAllFileNames(Constants.UploadDocumentsPath + companycode);
            for (String str : fileNames) {
                PolicyEntity policyEntity = new PolicyEntity();
                policyEntity.setFileName(str);
                fileNameList.add(policyEntity);
                log.info(str);
            }
            modelMap.put("list", fileNameList);

        }
        modelMap.put("companycode", companycode);
        modelMap.put("customername", customerInfo.getCustomername());
        return new ModelAndView("system/documents", modelMap);
    }

    @RequestMapping(value = "checkFileName.shtml")
    @ResponseBody
    public HashMap<String, Object> checkFileName(String fileName, Integer companycode) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        if (fileName != null && fileName.contains("\\")) {
            int lastIndexOf = fileName.lastIndexOf("\\");
            fileName = fileName.substring(lastIndexOf + 1);
        }
        File file = new File(Constants.UploadDocumentsPath + companycode + "\\" + fileName);
        if (file.exists()) {
            map.put("existFlag", true);
        } else {
            map.put("existFlag", false);
        }
        return map;
    }

    @RequestMapping(value = "upLoadDocuments.shtml")
    public ModelAndView upLoadDocuments(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, Integer companycode, ModelMap modelMap) {
        try {
            if (uploadfile != null) {
                String fileName = uploadfile.getOriginalFilename();
                File newfile = new File(Constants.UploadDocumentsPath + companycode + "\\" + fileName);
                uploadfile.transferTo(newfile);
            }
            modelMap.put("msg", "文件上传成功");
        } catch (IOException e) {
            modelMap.put("msg", "文件上传成功");
            e.printStackTrace();
        }
        return this.documentsInit(modelMap, companycode);
    }

    @RequestMapping(value = "downLoadDocuments.shtml")
    public void downLoadDocuments(String filename, Integer companycode, HttpServletResponse response, ModelMap modelMap) {
        String downloadPath = Constants.UploadDocumentsPath + companycode + "//" + filename;
        try {
            BufferedInputStream binput = new BufferedInputStream(new FileInputStream(downloadPath));
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"), "iso8859-1"));
            int len = 0;
            byte buffer[] = new byte[2048];
            OutputStream out = response.getOutputStream();
            while ((len = binput.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            binput.close();
        } catch (IOException e) {
            modelMap.put("msg", "文件下载失败！");
            e.printStackTrace();
        }
    }
}
